package dinh.org.myapp;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import model.Person;
import model.PersonValidator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import servicies.PersonService;

/**
 * Handles requests for the application home page.
 */
@Controller
@RequestMapping("/main")
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	private static final ApplicationContext appContext = new ClassPathXmlApplicationContext("/beans.xml");
	
	private int counter;
	
	@Autowired
	private PersonService personService;
	
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/persons", method = RequestMethod.GET)
	public ModelAndView getPersons() {
		logger.debug("Received request to show all person");
		ModelAndView modelAndView = (ModelAndView)appContext.getBean(ModelAndView.class);
		List<Person> persons = personService.getAll();
		modelAndView.addObject("persons",persons);
		modelAndView.setViewName("personspage");
		return modelAndView;
	}
	
	@RequestMapping(value = "/persons/add", method = RequestMethod.POST)
	public String add(@ModelAttribute("person") Person person, BindingResult result){
		logger.debug("Received request to add new person");
		new PersonValidator().validate(person, result);
		if(result.hasErrors()){
			return "editPage";
		}
		personService.save(person);
		return "editPage";
	}
		
	/*	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public ModelAndView AddPerson(String name, int age) {

		logger.debug("AddPerson");
		ModelAndView model = appContext.getBean(ModelAndView.class);
		Person person = appContext.getBean("person", Person.class);
		person.setName(name);
		person.setAge(age);
		model.setViewName("view");
		model.addObject("person", person);

		return model;

	}*/
}
